package
{
	import CExtends.extendBase;
	
	import CTitle.ct_data;
	import CTitle.ct_initializer;
	import CTitle.ct_title;
	
	import Classes.CLoader;
	import Classes.pi_events;
	
	import UIFree.ObjectEvent;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	import flash.system.Security;


	public class c_title extends extendBase {
		private var _dialog	: Object;
		private var _cy		: int;
		private var _title	: ct_title;
		private var _backList : Object;
		private var _fontList : Object;
		private var _textInput: Object;
		
		protected static const PNGCARDOBJECT: String = '[object pi_pngcard]'; 
		
		public function c_title() {
			super();
			Security.allowDomain('*');
			Security.loadPolicyFile(ct_data.backsURL + '/' + CLoader.CROSSDOMAINXML);
			addEventListener('PLUGINBTRELEASE', doShowDialog);
		}

		override public function init(a_app: Object, extendsLayer: Object): void {
			super.init(a_app, extendsLayer);
			_app.classes.cardbody.serviceClass['tlt'] = ct_initializer;
		}
		
		protected function initDialog(parent: Object): void {
			var inner: Rectangle = parent.getBounds(_app);
			inner.inflate(-10, -10);
			_dialog = new _app.classes.window(_app.layers[2], inner.x, inner.y, 
												230, 545,//435, 
												'window', false, 1);	
			_dialog.title.text = 'Текст к открытке';
			_cy = 0;
			createLabel('Фон');
			_backList = createList(117, ct_data.backs, function(area : Object, item: Object, index: int): Object {
				var c_item: Object = new _app.classes['label'](area, 0, index * 35, 180, 35, 'listItem');
				var preview: Object = new _app.classes['loader'](c_item, ct_data.backsURL + '/games/data/title_backs/preview/' + item.id + '.png', function(e: Event): void {
					var it_inner: Rectangle = c_item.getInner();
					preview.x = (it_inner.width - preview.width) / 2;
					preview.y = (it_inner.height - preview.height) / 2;
				});
//				c_item._data = item;
				return c_item;
			}, doBackSelect);

			createLabel('Шрифт');
			_fontList = createList(112, ct_data.fonts, function(area : Object, item: Object, index: int): Object {
				var c_item: Object = new _app.classes['label'](area, 0, index * 20, 180, 20, 'listItem');
				c_item.text = item.name;
				c_item._data = item;
				return c_item;
			}, doFontSelect);
			createLabel('Текст');
			
			_textInput = createLabel(ct_data.defaultText, 100, 'minput');
			_textInput.textField.addEventListener(Event.CHANGE, doTextChange);
			_cy += 5;
			createLabel('Отправляйте вместе с открытками небольшие сообщения! Требуется текст, две или три строки, в зависимости от размера ленточки', 78, 'description');
			
			var ok_button: Object = new _app.classes['button'](_dialog, 90, _cy + 17, 45, 30, 'button');
			ok_button.text = 'Ok';
			ok_button.addEvent(MouseEvent.CLICK, function(e: Event): void {
				_dialog.dispatchEvent(new Event(Event.CLOSE));				
			});
			
			var clear_button: Object = new _app.classes['button'](_dialog, 135, _cy + 17, 90, 30, 'button');
			clear_button.text = 'Убрать текст';
			clear_button.addEvent(MouseEvent.CLICK, doClear);
			
			_app.addEventListener('FULLVIEWCHANGE', function(e: Event): void {
				if (_app.isFullView && _dialog.visible) _dialog.slideHide();
			});
			
			backSelect(0);
		}
		
		protected function doClear(e: Event): void {
			if (_title) {
				_title.dispose();
				_title = null;
				_backList.selectIndex = -1;
				_fontList.selectIndex = -1;
			}
		}
		
		protected function backSelect(selectIndex: int): void {
			if (selectIndex > -1) {
				if (_fontList.selectIndex < 0) _fontList.selectIndex = 0;
				applyBackTitle(selectIndex);
			}
		}
		
		protected function doBackSelect(e: Event): void {
			backSelect(e.target.selectIndex);
		}
		
		protected function doFontSelect(e: Event): void {
			if (_fontList.selectIndex > -1) {
				if (_backList.selectIndex < 0) _backList.selectIndex = 0;
				applyFontTitle(e.target.selectIndex);
			}
		}
		
		public static function decode(text: String): String {
			var result	: String = '';
			var i		: int = 1;
			var bytes	: Array = text.split('x');
			while (i < bytes.length) {
				result += String.fromCharCode(parseInt(bytes[i], 16));
				i++;
			}
			return result;
		}
		
		public static function encode(text: String): String {
			var result	: String = '';
			var count	: int = text.length;
			for (var i:int=0; i<count; i++) {
				result += 'x' + text.charCodeAt(i).toString(16);
			}
			return result;
		}
		
		public function applyParam(a_backID: int, a_fontIndex: int, titleText: String): void {
			if (!_app.cardbody.maskInfo.extend) _app.cardbody.maskInfo.extend = new Object();
			
			_title.applyParam(a_backID, a_fontIndex, titleText);

			if (_backList.selectIndex > -1) 
				_app.cardbody.maskInfo.extend['tlt'] = _title.params;
			else delete(_app.cardbody.maskInfo.extend['tlt']);
		}
		
		protected function doTextChange(e: Event): void {
			checkTitle();
			if (_fontList.selectIndex < 0) _fontList.selectIndex = 0;
			if (_backList.selectIndex < 0) _backList.selectIndex = 0;
			applyParam(_title.backID, _title.fontIndex, _textInput.text);
		}
		
		protected function applyBackTitle(dataIndex: int): void {
			checkTitle();
			applyParam(ct_data.backs[dataIndex].id, _title.fontIndex, _textInput.text);
		}
		
		protected function applyFontTitle(dataIndex: int): void {
			checkTitle();
			applyParam(_title.backID, dataIndex, _textInput.text);
		}
		
		protected function checkTitle(): void {
			if (!_title) {
				_title = new ct_title(_app.editor.cardBody);
				_app.editor.cardBody.addEvent('DISPOSE', doClear);
			}
		}
		
		protected function doShowDialog(e: ObjectEvent): void {
			if (_app.editor.cardBody.hasOwnProperty('bitmap')) {
				if (!_dialog) initDialog(_app.extendsLayer);
				_dialog.slideShow();
			} else _app.alert(_app.classes.data.WARNING, 'Сообщение можно присоединять только к не анимационным открыткам.');
		}
		
		protected function createLabel(caption: String='',  a_height: int=25, a_class: String = 'lbLabel'): Object {
			var inner: Rectangle = _dialog.getInner();
			var label: Object = new _app.classes.label(_dialog, inner.x, inner.y + _cy + 5, inner.width, a_height, a_class);
			label.text = caption;
			_cy += a_height;
			return label;
		}
		
		protected function createList(a_height: int, a_list: Array, createItem: Function, doSelect: Function): Object {
			var inner: Rectangle = _dialog.getInner();
			var _list: Object = new _app.classes.list(_dialog, inner.x, inner.y + _cy, inner.width, a_height, 'list');
			_list.attachList(a_list, createItem);
			_list.addEvent('SELECT', doSelect);
			_cy += a_height;
			return _list;
		}
	}
}